<!-- 
  * Copyright (c) 2022 iSoftStone Information Technology (Group) Co.,Ltd.
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
 -->
<template>
	<view class="workBox">
		<view class="titleBox">
			{{num===1?'方案提交':num===3?'第一次作品提交':'第二次作品提交'}}
		</view>
		<view class="gitee">
			<u-form labelPosition="top" :model="form" ref="form" :rules="rules">
				<u-form-item label="大赛指定Gitee仓（仅代码）" labelWidth="200" labelStyle="style.styleLink" prop="link">
					<u-textarea :disabled="true" class="gitarea" height="72"
						placeholder="https://gitee.com/openharmony-sig/online_event/tree/master/solution_student_challenge">
					</u-textarea>
					<u--text text="点击复制链接" margin=" 10px 0 0 0" mode="link"
						href="https://gitee.com/openharmony-sig/online_event/tree/master/solution_student_challenge">
					</u--text>
				</u-form-item>

				<u-form-item label="作品说明" labelWidth="200" labelStyle="style.styleLink">
					<u-textarea :disabled="disabled" class="area" v-model="form.illustrate" ref="textarea" height="180"
						count maxlength="500" placeholder="可填写除代码外说明性文字或链接，链接可包含活动概述及演示文档、图片效果、作品视频文件等，形式不限。">
					</u-textarea>
				</u-form-item>
			</u-form>
		</view>
		<view class="fileBox">
			<u-row>
				<u-col :span="6">
					<u-text text="附件" bold></u-text>
				</u-col>
				<u-col :span="6">
					<view style="position: relative;">
						<u-upload @afterRead="afterRead" multiple accept="all" maxCount="3">
							<view class="btnAdd">
								<u-text text="添加附件" align="right" color="#4587F7" bold></u-text>
							</view>
						</u-upload>
					</view>
				</u-col>
			</u-row>
			<u-text text="数量限制:3个" margin="10px 0" color="#606266"></u-text>
			<u-text text="格式支持:pdf、doc、docx、mp4、pptx、xlsx、md" margin="10px 0" color="#606266"></u-text>
			<u-text text="单个大小限制:不超过20M" margin="10px 0" color="#606266"></u-text>
			<view class="fileList">
				<view class="fileItem" v-for="(item,index) in fileList" :key="index">
					<u--image :showLoading="true" :src="item.fileType" width="50px" height="70px"></u--image>
					<view class="title">
						<u-text :text="item.name" size="32rpx" bold lines='2' color="#606266"></u-text>
						<view style="position: absolute;bottom: 0;width: 100%;">
							<u-line-progress height="5" :showText="false" :percentage="100" activeColor="#4587F7">
							</u-line-progress>
						</view>
					</view>
					<view class="close">
						<u-icon name="close-circle-fill" color="#d0d2d8" size="80rpx" @click="deletePic(index)">
						</u-icon>
					</view>
				</view>
			</view>
		</view>
		<view style="width: 100%;height: 100px;"></view>
		<view class="bottom">
			<u-button :disabled="disabled" type="primary" shape="circle" @click="onSubmit()" :text="btnTxt"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		getWorkByOpenId,
		addActiveWork,
		appletWorkCheckEdit,
		editActiveWork
	} from '@/common/api.js';
	export default {
		data() {
			return {
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				fileList: [],
				//pdf、doc、docx、mp4、pptx、xlsx、md
				fileImg: {
					"pptx": "http://localhost::8989/file/image/activity/01-ppt.png",
					"xlsx": "http://localhost::8989/file/image/activity/02-excel.png",
					"docx": "http://localhost::8989/file/image/activity/03-word.png",
					"doc": "http://localhost::8989/file/image/activity/03-word.png",
					"pdf": "http://localhost::8989/file/image/activity/04-pdf.png",
					"other": "http://localhost::8989/file/image/activity/05-unknown.png",
				},
				style: {
					styleLink: "font-size: 32rpx;color: #000000;font-weight: bold;margin-bottom: 26rpx;"
				},
				value: "",
				form: {
					link: "https://gitee.com/openharmony-sig/online_event/tree/master/solution_student_challenge",
					illustrate: "",
					activityName: "",
					signupReason: "",
				},
				rules: {
					link: {
						required: false,
						message: '请输入作品链接',
						trigger: ['blur']
					},
					illustrate: {
						required: false,
						message: '请输入说明（文本框内不超过500字符，可填写除代码外说明性文字或链接，如：说明及演示文档、图片和视频等，形式不限）',
						trigger: ['blur'],
						max: 500
					},
				},
				disabled: false,
				btnTxt: "提交",
				setPlan: '',
				checkState: 0,
				num: 0,
				teamName: ""
			}
		},
		onLoad: function(res) {
			this.form.activityid = res.id
			this.num = parseInt(res.index) + 1
			this.form.openId = this.$store.state.$userInfo.openId
			this.form.wname = res.teamName
			this.teamName = res.teamName
			this.info()
		},
		methods: {
			info() {
				const data = {
					activityId: this.form.activityid - 0,
					openId: this.$store.state.$userInfo.openId,
					type: this.num
				}
				//通过openId和activityId获取作品详情
				getWorkByOpenId(data).then(res => {
					console.log(res, "这是作品信息")
					if (res.id) {
						this.form = res
						if (res.checkState === 1) {
							this.disabled = true
							this.btnTxt = "审核中"
						} else if (res.checkState === 2) {
							this.disabled = true
							this.btnTxt = "通过"
						} else if (res.checkState === 3) {
							this.disabled = false
							this.btnTxt = "再次提交"
						} else {
							this.disabled = true
							this.btnTxt = "提交"
						}
						if (this.num === 2 && !res.first_time) {
							this.disabled = false
							this.btnTxt = "再次提交"
							this.form.illustrate = ""
						} else if (this.num === 3 && !res.second_time) {
							this.disabled = false
							this.btnTxt = "再次提交"
						}
						if (res.linkList.length > 0) {
							this.fileList = []
							res.linkList.forEach((result, index) => {
								const obj = res.link.split(",")
								if (obj[index] !== " ") {
									const fileType = (obj[index]).split(".")[1]
									const fileTypeImg = this.fileImg[fileType] ? this.fileImg[fileType] :
										this
										.fileImg["other"]
									this.fileList.push({
										status: 'success',
										message: '',
										url: result,
										fileType: fileTypeImg,
										name: obj[index]
									})
								}

							})

							/* this.fileList.push({
								status: 'success',
								message: '',
								url: res.link
							}) */
						}
					}
				})
			},
			//作品审核关联编辑（驳回）
			appletCheckEdit() {
				const data = {
					id: this.setPlan.recordId,
				}
				appletWorkCheckEdit(data).then(res => {})
			},
			//点击按钮提交
			onSubmit() {
				this.$refs.form.validate().then(res => {
					//this.disabled = true
					if (this.num === 1) {
						this.form.planTime = this.$moment().format("YYYY-MM-DD HH:mm:ss")
						if (this.fileList.length === 0 && !this.form.illustrate) {
							uni.$u.toast("请至少填一项")
							return false
						}

					} else if (this.num === 2) {
						this.form.firstTime = this.$moment().format("YYYY-MM-DD HH:mm:ss")
					} else if (this.num === 3) {
						this.form.secondTime = this.$moment().format("YYYY-MM-DD HH:mm:ss")
					}
					this.form.link = " "
					this.form.illustrate = this.form.illustrate ? this.form.illustrate : " "
					this.form.linkList = []
					let nexttrue = false
					if (this.fileList.length > 0) {
						const link = []
						this.fileList.forEach(item => {
							link.push(item.url)
							this.form.linkList.push(item.url)
							if (item.url.indexOf("wxfile") !== -1) {
								nexttrue = true
							}
						})
						this.form.link = link.toString()
						if(nexttrue){
							uni.$u.toast("文件上传错误，请稍后重试")
						}
					}


					this.form.type = this.num
					this.form.wname = this.teamName
					this.disabled = true
					console.log(this.form, "获取作品上传信息")
					if (this.form.id) {
						this.btnTxt = "审核中"
						return editActiveWork(this.form).then(result => {
							const data = {
								id: this.form.recordId,
								checkState: 1
							}
							appletWorkCheckEdit(data).then(result => {
								uni.navigateBack({
									delta: 1, //返回层数，2则上上页
								})
							})
						})
					} else {
						this.btnTxt = "审核中"
						return addActiveWork(this.form).then(result => {
							uni.navigateBack({
								delta: 1, //返回层数，2则上上页
							})
						})
					}
				})
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				if ((this.fileList.length + event.file.length) > 3) {
					uni.$u.toast("上传附件最多3个")
					return false
				}
				uni.showLoading({
					title: "文件上传中",
					mask: true
				})
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList`].length
				let maxsize = true
				lists.map((item) => {
					const fileType = (item.name).split(".")[1]
					const fileTypeImg = this.fileImg[fileType] ? this.fileImg[fileType] : this.fileImg["other"]
					console.log(item, "item")
					item.fileType = fileTypeImg

					if (item.size > 20971520) {
						maxsize = false
					} else {
						this[`fileList`].push({
							...item,
							status: 'uploading',
							message: '上传中',
							fileType: fileTypeImg,
						})
					}
				})
				if (!maxsize) {
					uni.$u.toast("单个文件不能超过20M")
					return false
				}

				for (let i = 0; i < lists.length; i++) {
					console.log(lists, "lists")
					const result = await this.uploadFilePromise(lists[i].url, lists[i].name)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result,
						fileType: lists[i].fileType,
					}))
					fileListLen++
				}
				uni.hideLoading()
				console.log(this.fileList, "fileList")
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://localhost:/prod-api/richTextUpload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							type: 'name',
							name: name
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).data)
							}, 1000)
						}
					});
				})
			},
			deletePic(index) {
				this[`fileList`].splice(index, 1)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.workBox {

		.titleBox {
			background: #4587F7;
			padding: 10px;
			color: #FFF;
			text-align: center;
			font-size: 28rpx;

		}

		.gitee {
			margin-top: 16rpx;
			background: #FFFFFF;
			padding: 28rpx 24rpx 24rpx 24rpx;

			.content {
				.title {
					font-size: 32rpx;
					color: #000000;
					font-weight: bold;
					margin-bottom: 26rpx;
				}
			}

			.copy {
				font-size: 30rpx;
				color: #317AF7;
				text-align: center;
				line-height: 42rpx;
				font-weight: 400;
				margin-top: 36rpx;
			}

			/deep/ .u-input__content__field-wrapper {
				font-size: 28rpx;
				border-radius: 8rpx !important;
			}
		}

		.explain {
			margin-top: 16rpx;
			background: #FFFFFF;
			padding: 28rpx 24rpx 40rpx 24rpx;

			.content {
				.title {
					font-size: 32rpx;
					color: #000000;
					font-weight: bold;
					margin-bottom: 26rpx;
				}
			}

			.copy {
				font-size: 30rpx;
				color: #317AF7;
				text-align: center;
				line-height: 42rpx;
				font-weight: 400;
				margin-top: 36rpx;
			}

			/deep/.u-textarea__field {
				font-size: 28rpx;
				border-radius: 8rpx !important;
			}
		}

		.bottom {
			width: 94%;
			margin-left: 3%;
			height: 128rpx;
			line-height: 128rpx;
			position: fixed;
			bottom: 0;

			/deep/ .u-button {
				height: 96rpx;
				line-height: 96rpx;
				background: #4587F7;
				border-radius: 48rpx;

				color: #FFFFFF;
				text-align: center;
				font-weight: bold;
			}

			/deep/ .u-button__text {
				font-size: 32rpx !important;
			}
		}

		.fileBox {
			margin-top: 20px;
			padding: 20px;
			background-color: #FFF;
			position: relative;

			.btnAdd {
				position: absolute;
				right: 0;
				top: -10px;
			}

			.fileList {
				.fileItem {
					display: flex;
					flex-direction: row;
					margin-top: 50rpx;

					.title {
						width: 600rpx;
						padding: 0 20rpx;
						position: relative;
					}

					.close {
						position: relative;
						top: 5px;

					}
				}
			}
		}
	}
</style>
